package cmd

import (
	"fmt"
	"go-cmd/internal/utils"
	"go-cmd/top/process"
	"os"
	"time"

	tm "github.com/buger/goterm"
	"github.com/spf13/cobra"
)

var (
	duration       int
	n              int    // Number of processes displayed
	TOTAL_MEM_SIZE uint64 // bytes
)

var top = &cobra.Command{
	Use:   "top",
	Short: "the application list",
	Long:  "Show the top 10 apps, and you can see the pid, mem%, cpu% and so on information.",
	Run: func(cmd *cobra.Command, args []string) {
		tm.Clear()
		for {
			// clear console
			tm.Flush()
			tm.MoveCursor(1, 1)
			text := fmt.Sprintf("%-12s%-12s%-12s%-20s%-20s\n", "pid", "ppid", "%mem", "%cpu", "exec")
			output, e := process.Processes(n)
			if e != nil {
				fmt.Println("Execute top command failed, err=", e.Error())
				os.Exit(1)
			}
			utils.Sort(output)
			for i := 0; i < n; i++ {
				s := fmt.Sprintf("%-12d%-12d%-12.1f%-20.1f%-20s\n", output[i].Pid, output[i].PPid, output[i].MemPercent, output[i].CpuPercent, output[i].Exec)
				text += s
			}
			tm.Print(text)
			time.Sleep(time.Second * time.Duration(duration))
		}
	},
}

func init() {
	top.LocalFlags().IntVarP(&duration, "duration", "d", 1, "confirm the duration of update information")
	top.LocalFlags().IntVarP(&n, "number", "n", 20, "number of processes displayed")
}

func Execute() {
	err := top.Execute()
	if err != nil {
		fmt.Println("execute top failed, err=", err)
		os.Exit(1)
	}
}
